<template>
  <a-modal
    :title="title"
    :width="drawerWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :destroyOnClose="destoryClose"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="物资分类名称">
          <a-input placeholder="物资分类名称" v-decorator="['classifyName', validatorRules.classifyName]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="物资分类编码">
          <a-input placeholder="物资分类编码" v-decorator="['classifyCode', validatorRules.classifyCode]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :hidden="seen"
          label="上级分类">
          <a-tree-select
            style="width:100%"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="dataSource"
            :loadData="onLoadData"
            v-model="model.parentId"
            placeholder="无"
            :disabled="condition"
            :loadedKeys="loadedKeys"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注">
          <a-textarea placeholder="请输入备注" v-decorator="['remarks']"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@lone/lone-vue/src/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import { getAction } from '@lone/lone-vue/src/api/manage'
  const checkMmsMaterialClassify = (params)=>getAction("/base/mmsMaterialClassify/checkOnlyMmsMaterialClassify",params);
  export default {
    name: "MmsMaterialClassifyModal",
    data () {
      return {
        title:"操作",
        dataSource:[],
        destoryClose:true,
        visibleCheck: false,
        loadedKeys:[],
        visible: false,
        modalWidth:800,
        drawerWidth:700,
        model: {},
        seen:false,
        condition:true,
        versionId:'',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          classifyName:{rules: [{ required: true, message: '请输入物资分类名称' }]},
          classifyCode:{
            rules: [{
              required: true, message: '请输入物资分类编码',validator: this.validateClassifyCode,
            }]
          },
        },
        url: {
          add: "/base/mmsMaterialClassify/add",
          edit: "/base/mmsMaterialClassify/edit",
          searchQuery:'/base/mmsMaterialClassify/queryById'
        },
      }
    },
    created () {
    },
    methods: {
        validateClassifyCode(rule, value, callback){

          var params = {
            id:this.model.id,
            classifyCode:value
          };
          checkMmsMaterialClassify(params).then((res)=>{
            if(res.success){
              callback();
            }else{
              callback("物资编码已存在！");
            }
          });
        },
      add (classifyId) {
        this.visible = true;
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        this.model = Object.assign({}, {});
        if(classifyId){
          this.seen = false;
          this.condition = true;
          this.loadTree()
          this.model = Object.assign({}, {});
          this.model.parentId = classifyId!=null?classifyId.toString():null;
        }else{
          this.seen = true;
        }
      },

      edit (key) {
        this.condition = false;
        // this.seen = false;
        this.visible = true;
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        //选中节点加载当前节点的内容
        this.loadTree();
        getAction(this.url.searchQuery,{ id : key }).then((res)=>{
          if(res.success){
            this.model = Object.assign({}, res.result);
            this.model.parentId = res.result.parentId!=null?res.result.parentId.toString():null;
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model,'id','classifyName','parentId','classifyCode','isLeaf'))
            });
          }else{
            this.$message.warning(res.message);
          }
        })
      },

      //初始化加载方法
      loadTree (key = '') {
        getAction(`/base/mmsMaterialClassify/queryMmsMaterialClassifyTreeList`,{ key }).then((res) => {
          if (res.success) {
            this.dataSource = res.result
          }
        })
      },
      //展开节点调用此方法
      onLoadData (treeNode) {
        return new Promise((resolve) => {
          getAction('/base/mmsMaterialClassify/queryMmsMaterialClassifyTreeList',{ key:treeNode.dataRef.key }).then((res) => {
            if (res.success) {
              treeNode.dataRef.children = res.result;
              this.dataSource = [...this.dataSource]
              resolve()
            }
          })

        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
        // this.form.resetFields();
        // this.model = Object.assign({}, {});
        this.form.resetFields();
        this.loadedKeys=[];
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize(){
        let screenWidth = document.body.clientWidth;
        if(screenWidth < 500){
          this.drawerWidth = screenWidth;
        }else{
          this.drawerWidth = 700;
        }
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
    }
  }
</script>

<style lang="less" scoped>

</style>